/*
 * RefuellingXMLParser.java
 *
 * Created on 4 de Abril de 2006, 19:58
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.mobiletools.fuelmanager.model;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Vector;
import org.kxml2.io.KXmlParser;
import org.xmlpull.v1.XmlPullParserException;

/**
 *
 * @author instrutor
 */
public class RefuellingXMLParser {
    
    public static final int RETURN_MESSAGE = 0;
    public static final int RETURN_DATA    = 1;
    
    private static final String RESPONSE_TAG  = "resp";
    private static final String REFUELLING_TAG  = "ref";
    
    /** Creates a new instance of RefuellingXMLParser */
    private RefuellingXMLParser() {
    }
    
    public static int convertXML(String xml, Vector refuellings) throws UnsupportedEncodingException, XmlPullParserException, IOException{
        int returnCode = RETURN_MESSAGE;
        KXmlParser parser = new KXmlParser();
        ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes("utf-8"));
                
	parser.setInput(bais, "utf-8");

        if (parser.nextTag() != KXmlParser.END_DOCUMENT) {
            parser.require(KXmlParser.START_TAG, null,RESPONSE_TAG);

            while (parser.nextTag() == KXmlParser.START_TAG) {
                parser.require(KXmlParser.START_TAG, null,REFUELLING_TAG);

                String date          = parser.getAttributeValue(null, "date");
                Date refDate = new Date(Long.parseLong(date));
                String odometerP     = parser.getAttributeValue(null, "odometerP");
                String odometerT     = parser.getAttributeValue(null, "odometerT");
                String gasLiters     = parser.getAttributeValue(null, "gasLiters");
                String gasValue      = parser.getAttributeValue(null, "gasValue");
                String alcoholLiters = parser.getAttributeValue(null, "alcoholLiters");
                String alcoholValue  = parser.getAttributeValue(null, "alcoholValue");
                String comment       = parser.getAttributeValue(null, "comment");
                
                refuellings.addElement(new Refuelling(refDate,odometerP,odometerT,gasLiters,gasValue,alcoholLiters,alcoholValue,comment));
                
                parser.nextTag();
            }

            parser.require(KXmlParser.END_TAG, null,RESPONSE_TAG);
            parser.next();
            parser.require(KXmlParser.END_DOCUMENT, null, null);

        }

        
        return returnCode;
    } 
}
